package com.techfansy.photo;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;

import java.lang.reflect.Field;

/**
 * Created by lenovo on 2016/8/9.
 */
public class UIUtils {

    /**
     * 屏幕的宽度
     */
    private static int sScreenWidth;

    /**
     * 屏幕的高度
     */
    private static int sScreenHeight;

    /**
     * 屏幕的密度
     */
    private static float sDensity;

    /**
     * 状态栏高度
     */
    private static int sStatusBarHeight;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static void init(Context context) {
        sDensity = context.getResources().getDisplayMetrics().density;
        Display display = getDisplay(context);

        Point realSize = new Point();
        int sdkVersion = Build.VERSION.SDK_INT;
        if(sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            display.getRealSize(realSize);
            sScreenWidth = realSize.x;
            sScreenHeight = realSize.y;
        }else{
            sScreenWidth = display.getWidth();
            sScreenHeight = display.getHeight();
        }
        initStatusBarHeight(context);
    }

    private static void initStatusBarHeight(Context context) {

        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sStatusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getStatausHeight() {
        return sStatusBarHeight;
    }

    private static Display getDisplay(Context context) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue)
    {
        return (int) (dpValue * sDensity + 0.5f);
    }


    /**
     * 根据手机的分辨率�?dp 的单�?转成�?px(像素)
     */
    public static int dip2px(Context context, float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 得到WindowManager的操作比较�?时，因此缓存宽高
     *
     * @return display
     */

    public static int getScreenWidth() {
        return Math.min(sScreenWidth, sScreenHeight);
    }

    public static int getScreenHeight() {
        return Math.max(sScreenWidth, sScreenHeight);
    }

}
